﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace FC.Utils
{
    public static class Converts
    {
        /// <summary>
        /// 自动类型转换，可以将该类的对象按照属性的对应关系自动转换为其他类的对象
        /// </summary>
        /// <typeparam name="T">该类类型</typeparam>
        /// <typeparam name="H">目标类类型</typeparam>
        /// <param name="o">该类的对象</param>
        /// <param name="that">目标类对象</param>
        /// <returns>目标类对象</returns>
        public static H Convert<T, H>(this T o, H that) where T : class where H : class
        {
            //获取 T 的类型
            Type typeT = typeof(T);
            //获取 H 的类型
            Type typeH = typeof(H);

            //获取 T 类型的所有公共属性
            List<PropertyInfo> propertiesT = new List<PropertyInfo>(typeT.GetProperties());
            //获取 H 类型的所有公共属性
            List<PropertyInfo> propertiesH = new List<PropertyInfo>(typeH.GetProperties());

            foreach (var pT in propertiesT)
            {
                PropertyInfo pH = null;
                if (pT.Name == "Id")
                {
                    string temp = typeT.Name + "Id";
                    pH = propertiesH.Find(x => (x.Name == typeT.Name + "Id" && x.PropertyType == pT.PropertyType) || (x.Name == pT.Name && x.PropertyType == pT.PropertyType));
                }
                else
                {
                    //在 H 类型中 查找与 T 类型对应的属性
                    pH = propertiesH.Find(x => x.Name == pT.Name && x.PropertyType == pT.PropertyType);
                }
                if (pH != null)
                {
                    pH.SetValue(that, pT.GetValue(o), null);
                }
                else
                {
                    pH = propertiesH.Find(x => x.Name == pT.Name && x.PropertyType == typeof(string));
                    if(pH != null)
                    {
                        pH.SetValue(that, pT.GetValue(o).ToString(), null);
                    }
                }
            }

            return that;
        }

        /// <summary>
        /// 自动类型转换，可以将该类的列表按照属性的对应关系自动转换为其他类的列表
        /// </summary>
        /// <typeparam name="T">该类类型</typeparam>
        /// <typeparam name="H">目标类类型</typeparam>
        /// <param name="list">该类的列表</param>
        /// <param name="those">目标类列表</param>
        /// <returns>目标类对象</returns>
        public static List<H> Convert<T, H>(this List<T> list, List<H> those) where T : class where H : class
        {
            foreach (var item in list)
            {
                H obj = Activator.CreateInstance<H>();
                item.Convert(obj);
                those.Add(obj);
            }
            return those;
        }
    }
}
